<template>
  <div class="app-container">
    <!--区域数据-->
    <el-col :span="4" style="height: 100%;padding-left: 0;">
      <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
        <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                  style="width: 100%;" v-model="filterText"/>
        <div style="height: 96%; max-height:96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
          <el-tree
            :data="sheetsTreeList"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            :default-expanded-keys="defaultExpandedKeys"
            highlight-current
            v-loading="treeLoading"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data}">
              <div class="custom-tree-node" style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                <span>{{ node.label }}</span>
                <!-- <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span> -->
              </div>
            </template>
          </el-tree>
        </div>
      </div>
    </el-col>
    <el-col :span="20" style="height: 100%;background-color: #FFFFFF;padding: 10px;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <!-- <el-form-item label="公摊名称" prop="publicShareName">
          <el-input
            v-model="queryParams.publicShareName"
            placeholder="请输入公摊名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <el-form-item label="所属公摊" prop="publicShareId">
          <el-select v-model="queryParams.publicShareId" clearable placeholder="请选择所属公摊">
            <el-option v-for="item in publicShareList"
              :key="item.id"
              :label="item.publicShareName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="能源类型" prop="energyType">
          <el-select v-model="queryParams.energyType" placeholder="请选择能源类型">
            <el-option v-for="dict in dict.type.energy_use_classification"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户编号" prop="userId">
                    <!-- <el-input :size="formItemSize"
                              v-model="queryParams.userId"
                              placeholder="请输入用户编号"
                              clearable
                              @keyup.enter.native="handleQuery"
                    /> -->
                    <el-select
                    :filter-method="dataFilterQuery"
                      style="width: 100%;"
                      :size="formItemSize"
                      v-model="queryParams.userId"
                      
                      placeholder="请选择用户"
                      filterable
                      clearable
                      
                    >
                      <el-option
                        v-for="userXb in userXbOptionQuery"
                        :key="userXb.id"
                        :label="userXb.userName"
                        :value="userXb.userId"
                      >
                        <span style="float: left">{{ userXb.userId }}</span>
                        <span
                          style="float: right; color: #8492a6; font-size: 13px"
                          >{{ userXb.userName }}</span
                        >
                      </el-option>
                    </el-select>
                  </el-form-item>
        <!-- <el-form-item label="用户编号" prop="userId">
            <el-input v-model="queryParams.userId" placeholder="请输入用户编号" clearable @keyup.enter.native="handleQuery" />
          </el-form-item> -->
        
        <el-form-item label="日期" prop="reportDate">
          <el-date-picker v-model="queryParams.reportDate" value-format="yyyy-MM" type="month" placeholder="请选择">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>

           <RightDropdown
                :showSearch.sync="showSearch"
                @queryTable="getList"
                :tableVisible="false"
                :queryVisible="false"
                @export="handleExport"
                class="ml10"
              ></RightDropdown>

        </el-form-item>
      </el-form>

      <el-table border v-loading="loading" :data="reportList" show-summary :summary-method="getSummaries">
        <el-table-column type="index" align="center" width="50" label="序号"></el-table-column>
        <el-table-column label="所属区域" align="center" prop="areaName"  :show-overflow-tooltip="true"/>
        <el-table-column label="公摊名称" align="center" prop="publicShareName"  :show-overflow-tooltip="true"/>
        <!-- <el-table-column label="能耗类型" align="center" prop="energyType" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.energy_use_classification" :value="scope.row.energyType"/>
          </template>
        </el-table-column> -->
        <el-table-column label="用户编号" align="center" prop="userId" />
        <el-table-column label="用户名称" align="center" prop="userName" :show-overflow-tooltip="true"/>
        <el-table-column label="日期" align="center" prop="reportDate" />
       

        <el-table-column label="公摊生产和" align="center" prop="publicShareTotalAmount" />
        <el-table-column label="公摊消费和" align="center" prop="publicShareAlluserAmount" />
        <el-table-column label="该用户用量" align="center" prop="publicShareOneuserAmount" />

        <el-table-column label="占比（%）" align="center" prop="publicShareCoefficient" >
        <template slot-scope="scope">
           {{(scope.row.publicShareCoefficient * 100).toFixed(4) }}
          </template>
        </el-table-column>
       
        <el-table-column label="单价" align="center" prop="price" />
        <el-table-column label="分摊用量" align="center" prop="publicShareAmount" />
        <el-table-column label="费用" align="center" prop="publicShareCost" />
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-col>
  </div>
</template>

<script>
  import { listUsersxbAll } from "@/api/record/usersxb";
  import {getAllPublicShare} from "@/api/basedata/publicShare";
  import {selectConsumeReportList} from "@/api/basedata/publicShareComsumeReport";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import moment from "moment/moment";
  export default {
  name: "TotalReport",
  components: {Treeselect},
  dicts: ['energy_use_classification','public_share_calc_type','public_share_type'],
  data() {
    return {
       // 用户下拉框中的数据
      userXbOption: [],
      userXbOptionCopy: [],
      userXbOptionQuery: [],
      userOption:[],
      totalSummary:0,
      publicShareAmountSum:0,
      publicShareCostSum:0,
      // 区域树选项
      sheetsTreeList: [],
      defaultProps: {
        children: "children",
        label: "sheetsName",
      },
      filterText: '',
      treeLoading: false,
      treeWidth: '',
      defaultExpandedKeys: [],

      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报表表格数据
      reportList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantId: null,
        sheetsCode:null,
        areaId: null,
        publicShareName: null,
        publicShareId:null,
        energyType: '1',
        reportDate:moment().add(-1,'months').format("yyyy-MM"),
      },
      // 表单参数
      form: {},
      // 表单校验
      publicShareList:[]
    };
  },
  created() {
    this.getTreeList();
    this.getAllPS();
    // this.screenHeight = document.body.clientHeight
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  mounted() {
    this.getUserXbList();
    //this.getUserXbList();
    this.getList();
    this.treeWidth = this.$refs['tree']?.$el.offsetWidth - 15
  },
  methods: {
    getUserXbList() {
      listUsersxbAll().then((response) => {
        this.userXbOption = response.rows;
        this.userXbOptionCopy = response.rows;
        this.userXbOptionQuery = response.rows;
      });
    },
    dataFilter(val) {
        if (val) { //val存在
          this.userXbOption = [];
          this.userXbOption = this.userXbOptionCopy.filter((item) => {
          if (!!~item.userName.indexOf(val) || !!~item.userName.toUpperCase().indexOf(val.toUpperCase())
             || !!~item.userId.indexOf(val) || !!~item.userId.toUpperCase().indexOf(val.toUpperCase()) ) {
                return true
             }
          })
        } else { //val为空时，还原数组
          this.userXbOption = this.userXbOptionCopy;
        }
        this.$forceUpdate();
      },
     dataFilterQuery(val) {
        if (val) { //val存在
          this.userXbOptionQuery = [];
          this.userXbOptionQuery = this.userXbOptionCopy.filter((item) => {
          if (!!~item.userName.indexOf(val) || !!~item.userName.toUpperCase().indexOf(val.toUpperCase())
             || !!~item.userId.indexOf(val) || !!~item.userId.toUpperCase().indexOf(val.toUpperCase()) ) {
                return true
             }
          })
        } else { //val为空时，还原数组
          this.userXbOptionQuery = this.userXbOptionCopy;
        }
        this.$forceUpdate();
      },
    // getUserXbList(){
    //  listUsersxbAll().then(response => {
    //     this.userOption = response.rows;
    //   })
    // },
    handleExport() {
      this.download('datastatistics/publicShareComsumeReport/exportComsumeReportList', {
        ...this.queryParams
      }, `用户公摊明细_${new Date().getTime()}.xlsx`)
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      if(data.length>0){
        columns.forEach((column, index) => {
          if (index === 0) { sums[index] = '合计'; return; }
          if (index >= 1 && index <= 10) { sums[index] = '/'; return; }
           if (index == 11 ) { sums.splice(index,1,parseFloat(this.publicShareAmountSum).toFixed(4)); return; }
            if (index == 12) { sums.splice(index,1,parseFloat(this.publicShareCostSum).toFixed(4)); return; }
          //  sums.splice(index,1,parseFloat(this.totalSummary).toFixed(2));
          // const values = data.map(item => Number(item[column.property]));
          // if (!values.every(value => isNaN(value))) {
          //   sums[index] = values.reduce((prev, curr) => {
          //     const value = Number(curr);
          //     if (!isNaN(value)) {
          //       return prev + curr;
          //     } else {
          //       return prev;
          //     }
          //   }, 0);
          //   // sums[index] += ' ';
          //   sums[index] = parseFloat(sums[index]).toFixed(2);
          // } else {
          //   sums[index] = 'N/A';
          // }
        });
      }
      return sums;
    },
    getAllPS(aId){
      getAllPublicShare({areaId:aId}).then(response => {
        this.publicShareList = response.data;
      });
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      this.sheetsTreeList = JSON.parse(localStorage.getItem('meteredTreeData'))
      if (this.sheetsTreeList.length === 0){
        this.treeLoading = false;
      }else{
        this.defaultExpandedKeys = [this.sheetsTreeList[0].id];
        this.sheetsTreeList.map(item => {
          this.getLeafKeys(item)
        })
        this.treeLoading = false;
      }
    },
    getLeafKeys(node) {
      //判断是否要禁用的条件
      if (node.deviceType === 0 && node.children.length === 0) {
        node.isDisabled = true
      } else {
        node.isDisabled = false
      }
      node.children.forEach(item => this.getLeafKeys(item))
    },
    handleNodeClick(data) {
      // this.queryParams.areaId = data.id;
      this.queryParams.sheetsCode = data.sheetsCode;
      this.getAllPS(data.id);
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.sheetsName.indexOf(value) !== -1;
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: '' + node.id,
        label: node.sheetsName,
        children: node.children,
        isDisabled: node.isDisabled
      };
    },
    // 区域下拉框改变触发事件
    handleSheetsChange(node) {
      this.form.areaId = node.id
    },

    /** 查询公摊配置表列表 */
    getList() {
      this.loading = true;
      this.queryParams.reportType = 2;//先默认月报
      console.log(this.queryParams);
      selectConsumeReportList(this.queryParams).then(response => {
        this.reportList = response.rows;
        this.total = response.total;
        // this.totalSummary = response.summary;
        console.log( response)
         console.log( response.summaryMap)
        this.publicShareAmountSum = response?.summaryMap?.publicShareAmountSum;                             
        this.publicShareCostSum = response?.summaryMap?.publicShareCostSum;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tenantId: null,
        areaId: null,
        publicShareName: null,
        energyType: '1',
        reportDate:moment().add(-1,'months').format("yyyy-MM"),
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  }
};
</script>

<style scoped lang="scss">
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node {
    width: fit-content;
    min-width: var(--treeWidth);
  }

  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;

    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }
  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
.form_col {
  width: 80%;

  ::v-deep .el-form {
    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 23%;
  }
}
.form_query {
  width: 20%;
  text-align: right;
}
</style>